package interface_layer;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database_layer.Common;

import processing_layer.Course;

/**
 * This servlet is part of the AJAX search mini-application.
 * After receiving a request, it processes the values, and collects the
 * Intermediate results from the DB. After calculating them, it returns the
 * top values to the javascript code, which then loads the results asynchronously.
 * 
 * Please note that we used a disjunctive form, in which we search for the existence of
 * one parameter each time.
 */
public class SearchCourse extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
    private static final int topScores = 100;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchCourse()
    {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
	{
		try
		{
			int numberOfParams = Integer.parseInt(request.getParameter("numofparams"));
			HashMap<String,Integer> coursesScores = new HashMap<String, Integer>();
			HashMap<String,Course> coursesMap = new HashMap<String, Course>(); 
			int min,count = 0;
			int scores[] = new int[topScores];
			ArrayList<String> topCourses = new ArrayList<String>(); 
			
			for (int i = 0; i < numberOfParams; i++)
			{
				//1. run the query for each request.getParameter("param"+i));
				HashMap<String,Course> coursesFound = processing_layer.SearchProxy.queryForParameter
														(request.getParameter("param"+i),coursesScores);
				//2. keep all courses found in hashmap from coursename to its desc
				if (coursesFound.isEmpty())
				{
					continue;
				}
				coursesMap.putAll(coursesFound);
			}
			//4. extract top "topScores" scored courses.
			response.getWriter().print("<ul>");
			if (coursesMap.isEmpty())
			{
				response.getWriter().print("<li>Found nothing.</li></ul>");
				return;
			}
	
			
			min = 0;
			for (int i = 0; i < topScores; i++)
			{
				scores[i] = 0;
				topCourses.add("");
			}
			for (String courseFound : coursesMap.keySet())
			{
				if (coursesScores.get(courseFound)> min )
				{
					count++;
					topCourses.set(topScores - 1, courseFound);
					scores[topScores - 1] = coursesScores.get(courseFound);
					for (int i = topScores - 2; i >= 0; i--)
					{
						if ( coursesScores.get(courseFound) > scores[i] )
						{
							String tempString = topCourses.get(i);
							int tempScore = scores[i];
							topCourses.set(i, courseFound);
							scores[i] = coursesScores.get(courseFound);
							scores[i+1] = tempScore;
							topCourses.set(i+1, tempString);
						}
						else
						{
							break;
						}
					}
					min = scores[topScores - 1];
				}
			}
			if (count > topScores)
			{
				count = topScores;
			}
			for (int i = 0; i < count; i++)
			{
				response.getWriter().print("<li><span style=\"color:black\"><u><b>"+ 
						"<a href=\"courseDetails.jsp?course=" + topCourses.get(i) + "\">" + topCourses.get(i) + "</a>"+ "</b></u></span><br/>");
			}
			response.getWriter().print("</ul>");
			return;
		}
		catch (Exception e)
		{
			System.out.println("Exception is : " + e.getLocalizedMessage());
			ErrorHandler.parseForErrors(Common.INTERNAL_ERROR, response, null);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
	{
		doGet(request,response);
	}

}
